package com.spr.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spr.exception.StudentNotFound;
import com.spr.model.Schedule;
import com.spr.model.Student;
import com.spr.repository.StudentRepository;

@Service
public class StudentServiceImpl implements StudentService {

	@Resource
	private StudentRepository studentRepository;
	
	@Override
	@Transactional
	public Student create(Student student) {
	
		return studentRepository.save(student);
	}

	@Override
	@Transactional
	public List<Student> findAll() {
		return studentRepository.findAll();
	}

	@Override
	@Transactional
	public Student findById(int id) {
		return studentRepository.findOne(id);
	}

	@Override
	@Transactional(rollbackFor=StudentNotFound.class)
	public Student update(Student s) throws StudentNotFound {
	      Student updatedStudent = studentRepository.findOne(s.getStudentID());
          
	      updatedStudent.setDateOfBirth(s.getDateOfBirth());
            updatedStudent.setEmail(s.getEmail());   
          updatedStudent.setFirstName(s.getFirstName());
          updatedStudent.setLastName(s.getLastName());
          updatedStudent.setGender(s.getGender());
          return studentRepository.save(updatedStudent);
	}

	@Override
	@Transactional(rollbackFor=StudentNotFound.class)
	public void delete(int id) {
		studentRepository.delete(id);
		
	}

	@Override
	public Student findByUserID(int id) {
		List<Student> list = studentRepository.findAll();
		
		for(int i = 0; i < list.size(); i++){
			if(list.get(i).getUserID() == id){
				return list.get(i);
			}
			
		}
		
		
		return null;
	}

}
